package com.infoauto.opc.gateway.messages.handler;

import com.infoauto.opc.gateway.messages.util.SerializeUtils;
import com.rabbitmq.client.Channel;
import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;

import java.io.IOException;

//RabbitMQ监听器
public class SimpleRabbitMQListener implements ChannelAwareMessageListener {

    private static Logger logger = LoggerFactory.getLogger(SimpleRabbitMQListener.class);

    private RabbitMQListener rabbitMQListener;

    private Class genericType;

    public SimpleRabbitMQListener(RabbitMQListener rabbitMQListener) {
        this.rabbitMQListener = rabbitMQListener;
        this.genericType = rabbitMQListener.getGenericType();
    }

    @Override
    public void onMessage(Message message, Channel channel) throws IOException {
        //交换器
        String exchangeName = message.getMessageProperties().getReceivedExchange();
        //队列
        String queueName = message.getMessageProperties().getConsumerQueue();
        //路由键
        String routingKey = message.getMessageProperties().getReceivedRoutingKey();
        //tag
        long tag = message.getMessageProperties().getDeliveryTag();
        Variant variant = new Variant("789");
        try {
            boolean result = rabbitMQListener.onMessage(exchangeName, routingKey, queueName,
                    SerializeUtils.deserialize(message.getBody(), genericType),variant);
            if (result) {
                //消息处理正确，手动应答消息
                channel.basicAck(tag, false);
            } else {
                //重新发送消息到队尾
                channel.basicNack(tag, false, true);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            //重新发送消息到队尾
            channel.basicNack(tag, false, true);
        }
    }
}
